import React, { Component, Suspense } from 'react';
import { connect } from 'dva';
import Highcharts from 'highcharts';
import { Form, Row, Col, Popover } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import router from 'umi/router';
import moment from 'moment';
//import {formate } from './utils'
import OrderAnalysisTable from './OrderAnalysisTable';
import triangle from '@/assets/triangle_left.svg';
import styles from './orderAnalysis.less';
import PageLoading from '@/components/PageLoading';
import { transferLanguage,getTimeDistance } from '@/utils/utils';

const IntroduceRow = React.lazy(() => import('./IntroduceRow'));


const colors = ['#1890ff', '#fa541c', '#bfbfbf', '#fadb14', '#13c2c2', '#a0d911'];
const clientHeight = (document.body.clientHeight - 80) / 2;

@connect(({ orderAnalysis, component, loading ,i18n}) => ({
  orderAnalysis,
  OrderStatusCountbyDate: orderAnalysis.OrderStatusCountbyDate,
  OrderStatusList: orderAnalysis.OrderStatusList,
  CustomerOrders: orderAnalysis.CustomerOrders,
  KPI: orderAnalysis.KPI,
  language:i18n.language,
}))
@Form.create()
export default class OrderAnalysis extends Component {
  constructor(props) {
    super(props);
    this.state = {
      time: new Date(),
      orderStatuvalue: {},
      customerOrders: [],
      categories: [],
      OrderShipped: [],
      ReadyShip: [],
      OrderPacked: [],
      OrderPicked: [],
      OrderReceived: [],
      salesData: [],
      flowData: {
        countIn: '',
        countOut: '',
        volume: []
      },
      stockData: {
        palletCount: '',
        utlilization: '',
        stockStatistics: []
      },
      orderData: {
        orderCountCompletion: 0,
        orderCountMonth: 0,
        orderCountTarget: 0,
      }
    };
  }
  timerID = null
  componentWillMount() {
    this.requestList()
    // this.timerID = setInterval(
    //   () => this.requestList(),
    //   // 300000
    //   10000
    // );
  }
  componentDidMount() {
    // this.PieChart();
    this.columnarChart();
    // setTimeout(() => {
    //     this.getHeight({ name: 'ant-form', key: 'formHeight' });
    //     this.setState({
    //       clientHeight: document.body.clientHeight,
    //     });
    //   }, 20);
  }

  requestList() {
    this.getOrderStatusCountbyDate();
    this.getCustomerOrders();
    this.getCrossChart();
    this.getSelectPalletFlow()
    this.getSelectStockStatistics()
    this.getSelectOrderStatistics()
  }

  componentWillUnmount() {
    clearInterval(this.timerID)
    this.timerID = null
  }

  // OCS进出托盘流量
  getSelectPalletFlow() {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectPalletFlow',
      callback: (data) => {
        this.setState({
          flowData: {
            countIn: data.countIn,
            countOut: data.countOut,
            volume: this.transition(data.volume)
          }
        })
      }
    })
  }

  // 查看OCS库存统计
  getSelectStockStatistics() {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectStockStatistics',
      callback: (data) => {
        this.setState({
          stockData: {
            palletCount: data.palletCount,
            utlilization: Number(parseFloat(data.utlilization * 100).toFixed(0)),
            stockStatistics: this.transition(data.stockStatistics, 'time')
          }
        })
      }
    })
  }

  // 
  getSelectOrderStatistics(params) {
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectOrderStatistics',
      callback: (data) => {
        this.setState({
          orderData: data
        })
      }
    })
  }

  transition(arr, type) {
    return arr.map(item => {
      return {
        x: type === 'time' ? item.date.slice(0, 7) : item.date,
        y: item.count
      }
    })
  }


  // 柱状图
  columnarChart() {
    let _this = this;
    const {
      categories,
      OrderShipped,
      ReadyShip,
      OrderPacked,
      OrderPicked,
      OrderReceived,
    } = this.state;

    var chart = Highcharts.chart('ColumnarChart', {
      chart: {
        type: 'column',
      },
      title: {
        // text: 'Warehouse Order Dashboard',
        // text:'仓库订单仪表盘'
        text: 'Warehouse Order Dashboard',
      },
      colors: ['#52c41a', '#a0d911', '#1890ff', '#13c2c2', '#bfbfbf', '#a0d911'],
      xAxis: {
        // categories: ['21-Apr', '22-Apr', '23-Apr', '24-Apr', '25-Apr', '26-Apr'],
        categories: categories,
      },
      credits: {
        enabled: false, // 默认值，如果想去掉版权信息，设置为false即可
        text: 'www.hcharts.cn', // 显示的文字
        href: 'http://www.hcharts.cn', // 链接地址
        position: {
          // 位置设置
          align: 'left',
          x: 400,
          verticalAlign: 'bottom',
          y: -100,
        },
        style: {
          // 样式设置
          cursor: 'pointer',
          color: 'red',
          fontSize: '30px',
        },
      },
      yAxis: {
        min: 0,
        title: {
          text: '',
        },
        stackLabels: {
          // 堆叠数据标签
          enabled: true,
          style: {
            fontWeight: 'bold',
            color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray',
          },
        },
      },

      tooltip: {
        formatter: function () {
          return (
            '<b>' +
            this.x +
            '</b><br/>' +
            this.series.name +
            ': ' +
            this.y +
            '<br/>' +
            'Total: ' +
            this.point.stackTotal
          );
        },
      },
      plotOptions: { 
        column: {
          stacking: 'normal',
          dataLabels: {
            enabled: true,
            color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
            style: {
              // 如果不需要数据标签阴影，可以将 textOutline 设置为 'none'
              textOutline: false,
            },
          },
        },
        series: {
          cursor: 'pointer',
          events: {
            click: function (event) {
              _this.showDetail(this.userOptions.key, event.point.category, '');
            },
          },
        },
      },
      series: [
        {
          // name: 'Order shipped',
          // name:'出库完成',
          name: transferLanguage('Analysis.field.OrderShipped',this.props.language),
          key: 'Order shipped',
          // data:OrderShipped|| [14, 15, 12, null, null, null],
          data: OrderShipped,
        },
        {
          key: 'Ready to ship',
          // name:'装车发货',
          name: transferLanguage('Analysis.field.Readytoship',this.props.language),
          // data: ReadyShip||[null, null, 3, 8, null, null],
          data: ReadyShip,
        },
        {
          key: 'Order packed',
          // name:'打包完成',
          name: transferLanguage('Analysis.field.OrderPacked',this.props.language),
          // data:OrderPacked|| [null, null, 1, 4, null, null],
          data: OrderPacked,
        },
        {
          key: 'Order picked',
          //name:'拣货完成',
          name: transferLanguage('Analysis.field.OrderPicked',this.props.language),
          // data:OrderPicked|| [null, null, null, 2, 5, null],
          data: OrderPicked,
        },
        {
          key: 'Order received',
          // name:'收货完成',
          name: transferLanguage('Analysis.field.OrderReceived',this.props.language),
          // data:OrderReceived|| [null, null, null, 2, 2, 6],
          data: OrderReceived,
        },
      ],
    });
  }
  
  nameFilter =(name)=>{
    let _name=[
      {code:transferLanguage('Analysis.field.OrderShipped',this.props.language),  value:'Order Shipped' },
      {code:transferLanguage('Analysis.field.ReadyToShip',this.props.language),  value:'Ready to Ship'},
      {code:transferLanguage('Analysis.field.OrderPacked',this.props.language),  value:'Order Packed'},
      {code:transferLanguage('Analysis.field.OrderPicked',this.props.language),  value:'Order Picked'},
      {code:transferLanguage('Analysis.field.OrderReceived',this.props.language),  value:'Order Received'},
    
    ]
    let value=_name.filter(v=>{
      return (v.code==name)||(v.value==name)
    })
    return value[0].code
  }

  // 饼图>
  PieChart = series => {
    let _this = this;
    Highcharts.chart('PieChart', {
      chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie',
      },
      colors: ['#1890ff', '#fa541c', '#bfbfbf', '#fadb14', '#13c2c2', '#a0d911'],
      title: {
        // text: 'Customer Distribution by Shipment',
        // text:'出货订单分布',
        text: 'Customer Distribution By Shipment',
      },
      tooltip: {
        pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>',
      },
      credits: {
        enabled: false, // 禁用版权信息
      },
      plotOptions: {
        pie: {
          allowPointSelect: true,
          cursor: 'pointer',
          dataLabels: {
            enabled: true,
            format: '<b>{point.name}</b>: {point.percentage:.1f} %',
            style: {
              color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black',
            },
          },
        },
        series: {
          cursor: 'pointer',
          events: {
            click: function (event) {
              let name = event.point.options.name
              name = name.substring(0, name.length - 3);
              const nowDate = moment(this.state.time).format('YYYY-MM-DD');
              _this.showDetail('', nowDate, name);
            },
          },
        },
      },
      series: series,
      // series: [
      //   {
      //     //   name: 'Brands',
      //     colorByPoint: true,
      //     data: [
      //       {
      //         name: '北京赛泰克（5）',
      //         y: 5,
      //         sliced: true,
      //         selected: true,
      //       },
      //       {
      //         name: '广州华粤（3）',
      //         y: 3,
      //       },
      //       {
      //         name: '上海百赛（3）',
      //         y: 3,
      //       },
      //       {
      //         name: '梅里亚（2）',
      //         y: 2,
      //       },
      //       {
      //         name: '北京伊诺凯（2）',
      //         y: 2,
      //       },
      //       {
      //         name: '济南汇世（1）',
      //         y: 1,
      //       },
      //     ],
      //   },
      // ],
    });
  };
  crossChart = (params) => {
    const { ontimeArrival, ontimeDelivery, whUtlilization, ontimeArrivalKpi, ontimeDeliveryKpi, whUtlilizationKpi } = params
    //横向柱状图：
    const dt = new Date();
    const m = (dt.getMonth() + 1 + '').padStart(2, '');
    var _m = new Array("January", "February", "March", "April", "May", "July", "Jul", "August", "September", "October", "November", "December");
    //if (/(ENM)/.test(m)) m = m.replace('ENM', _m);
    let _ENM = _m[dt.getMonth()]
    var chart = Highcharts.chart('Columnar', {
      chart: {
        type: 'bar',
      },
      title: {
        text: `${_ENM} KPI`,
        // text:`${m}月 (${_ENM})  KPI`, 
        // text: `${formatMessage({ id: `${m}月` })} KPI`
      },
      //   subtitle: {
      //     text: ' Wikipedia.org',
      //   },
      options3d: {
        enabled: true,
        alpha: 10,
        beta: 25,
        depth: 70,
        viewDistance: 100, // 视图距离，它对于计算角度影响在柱图和散列图非常重要。此值不能用于3D的饼图
        frame: {
          // Frame框架，3D图包含柱的面板，我们以X ,Y，Z的坐标系来理解，X轴与 Z轴所形成
          // 的面为bottom，Y轴与Z轴所形成的面为side，X轴与Y轴所形成的面为back，bottom、
          // side、back的属性一样，其中size为感官理解的厚度，color为面板颜色
          bottom: {
            size: 10,
          },
          side: {
            size: 1,
            color: 'transparent',
          },
          back: {
            size: 1,
            color: 'transparent',
          },
        },
      },
      xAxis: {
        // categories: ['Ontime arrival', 'Ontime delivery', 'WH utlilization'],

        categories: [
          transferLanguage('Analysis.field.OntimeArrival',this.props.language),
          transferLanguage('Analysis.field.OntimeDelivery',this.props.language),
         transferLanguage('Analysis.field.WhUtlilization',this.props.language),
        ],
        title: {
          text: null,
        },
        plotLines: [
          {
            color: 'red', //线的颜色，定义为红色
            dashStyle: 'solid', //标示线的样式，默认是solid（实线），这里定义为长虚线
            value: 9, //定义在哪个值上显示标示线，这里是在x轴上刻度为3的值处垂直化一条线
            width: 2, //标示线的宽度，2px
          },
        ],
      },
      colors: ['#1890ff', '#15E072', '#2f54eb'],
      yAxis: {
        min: 50,
        max: 100,
        title: {
          text: '',
          align: 'high',
        },
        labels: {
          overflow: 'justify',
        },
      },
      tooltip: {
        valueSuffix: '%',
      },
      credits: {
        enabled: false, // 禁用版权信息
      },
      plotOptions: {
        bar: {
          dataLabels: {
            crop: true,
            inside: true,
            align: 'right',
            allowOverlap: true,
            enabled: true,
            allowOverlap: true, // 允许数据标签重叠
            style: {
              // 如果不需要数据标签阴影，可以将 textOutline 设置为 'none'
              textOutline: false,
            },
          },
        },
        series: {
          borderWidth: 0,
          dataLabels: {
            enabled: true,
            format: '{point.y:.1f}%',
            style: {
              // 如果不需要数据标签阴影，可以将 textOutline 设置为 'none'
              textOutline: true,
            },
          },
        },
      },
      legend: {
        layout: 'vertical',
        align: 'right',
        verticalAlign: 'top',
        x: -40,
        y: 0,
        floating: true,
        borderWidth: 1,
        backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF',
        shadow: true,
      },
      series: [
        {
          name: 'Completion',
          data: [ontimeArrival, ontimeDelivery, whUtlilization],
        },
        {
          type: 'scatter',
          name: 'KPI',
          data: [
            {
              //   y: ontimeArrival < 88 ? 88 : ontimeArrival,
              y: ontimeArrivalKpi,
              marker: {
                symbol: 'url(' + triangle + ')',
                // symbol:'triangle-down',
              },
            },
            {
              y: ontimeDeliveryKpi,
              //   y: ontimeDelivery < 88 ? 88 : ontimeDelivery,
              marker: {
                symbol: 'url(' + triangle + ')',
              },
            },
            {
              y: whUtlilizationKpi,
              //   y: whUtlilization < 88 ? 88 : whUtlilization,
              marker: {
                symbol: 'url(' + triangle + ')',
              },
            },
          ],
        },
      ],
    });
  };
  // 柱状图 获取数据
  getOrderStatusCountbyDate = () => {
    const nowDate = moment(this.state.time).format('YYYY-MM-DD');
    let oldDate = '2020-04-02';
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectOrderStatusCountbyDate',
      payload: { timeNode: nowDate },
      callback: data => {

        let categories = [];
        let OrderShipped = [];
        let ReadyShip = [];
        let OrderPacked = [];
        let OrderPicked = [];
        let OrderReceived = [];
        (data || []).map(v => {
          categories.push(v.date);
          OrderShipped.push(this.handZore(v.orderShipped));
          ReadyShip.push(this.handZore(v.readyToShip));
          OrderPacked.push(this.handZore(v.orderPacked));
          OrderPicked.push(this.handZore(v.orderPicked));
          OrderReceived.push(this.handZore(v.orderReceived));
        });
        this.setState(
          {
            orderStatuvalue: data,
            categories,
            OrderShipped,
            ReadyShip,
            OrderPacked,
            OrderPicked,
            OrderReceived,
          },
          () => {
            this.columnarChart();
          }
        );
      },
    });
  };
  handZore = (zore) => {
    if (zore === 0) {
      return zore = ''
    }
    return zore
  }
  // 饼图 获取数据
  getCustomerOrders = () => {
    const nowDate = moment(this.state.time).format('YYYY-MM-DD');
    let oldDate = "2019-04-02";
    let overDate = "2020-06-11";
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectCustomerOrders',
      payload: { beginTime: nowDate, overTime: nowDate },
      callback: data => {
        const customerOrders = data.map((v, i) => {
          return { name: v.receiver + "（" + v.count + "）", y: v.count ? Number(v.count) : 0 }
        })
        const series = [{
          colorByPoint: true,
          data: customerOrders
        }]
        this.PieChart(series)
      },
    });
  }
  // 横向柱形图 获取数据
  getCrossChart = () => {
    const nowDate = moment(this.state.time).format('YYYY-MM-DD');
    const { dispatch } = this.props;
    dispatch({
      type: 'orderAnalysis/selectKPI',
      payload: { timeNode: nowDate },
      callback: data => {
        let ontimeArrival = parseFloat(data.ontimeArrival * 100).toFixed(2)
        let ontimeDelivery = parseFloat(data.ontimeDelivery * 100).toFixed(2)
        let whUtlilization = parseFloat(data.whUtlilization * 100).toFixed(2)
        let ontimeArrivalKpi = parseFloat(data.ontimeArrivalKPI * 100).toFixed(2)
        let ontimeDeliveryKpi = parseFloat(data.ontimeDeliveryKPI * 100).toFixed(2)
        let whUtlilizationKpi = parseFloat(data.whUtlilizationKPI * 100).toFixed(2)
        ontimeArrival = Number(ontimeArrival)
        ontimeDelivery = Number(ontimeDelivery)
        whUtlilization = Number(whUtlilization)
        ontimeArrivalKpi = Number(ontimeArrivalKpi)
        ontimeDeliveryKpi = Number(ontimeDeliveryKpi)
        whUtlilizationKpi = Number(whUtlilizationKpi)
        this.crossChart({ ontimeArrival, ontimeDelivery, whUtlilization, ontimeArrivalKpi, ontimeDeliveryKpi, whUtlilizationKpi })
      },
    });

  }

  showDetail = (name, type, customer) => {
    this.setState({
      statusShip: name,
    });
    router.push({
      pathname: `/portal/corelle/myOrderList`,
      query: {
        statusShip: encodeURI(name),
        dateTime: type,
        nameShip: encodeURI(customer),
      },
    });
  };
  render() {
    return (
      <div>
        <Suspense fallback={<PageLoading />}>
          <IntroduceRow flowData={this.state.flowData} stockData={this.state.stockData} orderData={this.state.orderData} visitData={this.state.salesData} />
        </Suspense>
        <Row gutter={12}>
          <Col span={12}>
            <div
              id="ColumnarChart"
              style={{ minWidth: '400px', height: clientHeight + 'px' }}
            ></div>
          </Col>
          <Col span={12}>
            <div
              id="myTable"
              style={{ minWidth: '400px', height: clientHeight + 'px', background: '#fff' }}
            >
              <OrderAnalysisTable />
            </div>
          </Col>
        </Row>
        <Row style={{ marginTop: 10 }} gutter={12}>
          <Col span={12}>
            <div id="PieChart" style={{ minWidth: '400px', height: clientHeight + 'px' }}></div>
          </Col>
          <Col span={12}>
            <div id="Columnar" style={{ minWidth: '400px', height: clientHeight + 'px' }}></div>
          </Col>
        </Row>
      </div>
    );
  }
}
